package com.sjb.thread;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 有点儿意思
 * @Description:
 */
public class CycleBarrierDemo {
    public static void main(String[] args) {
       CyclicBarrier cyclicBarrier =  new CyclicBarrier(3, new Runnable() {
            @Override
            public void run() {
                System.out.println("All threads have reached the barrier");
            }
        });
        for (int i = 1; i <= 3; i++) {
            new Thread(new Worker(i,cyclicBarrier)).start();
        }
    }


    static class Worker implements Runnable{
        private int id;
        private CyclicBarrier cyclicBarrier;

        public Worker(int id,CyclicBarrier cyclicBarrier){
            this.id = id;
            this.cyclicBarrier = cyclicBarrier;
        }

        @Override
        public void run() {
            try {
                System.out.println("Worker " + id + "is working.");
                Thread.sleep((long)(Math.random() * 200));
                System.out.println("Worker " + id + "has reached the barrier");
                cyclicBarrier.await();
                System.out.println("Worker " + id + "is counting the work");
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }

        }
    }
}
